import Request from './request'
import myconfig from "@/config";
import {
	apiObj
} from "@/utils/api-obj"
 
const http = new Request()

//接口加解密，以及参数，方法等初始化
const REQ_HOST = process.env.NODE_ENV === "production" ? myconfig.baseUrl.pro : myconfig.baseUrl.dev;




const getAuthSign = (token,req_time) => {
	var signArr = [token,req_time,myconfig.AUTH_SIGN_KEY];
	return md5js.hex_md5(md5js.hex_md5(signArr.join('-')));
}



http.setConfig((config) => { /* 设置全局配置 */
	return config
})

/**
 * 自定义验证器，如果返回true 则进入响应拦截器的响应成功函数(resolve)，否则进入响应拦截器的响应错误函数(reject)
 * @param { Number } statusCode - 请求响应体statusCode（只读）
 * @return { Boolean } 如果为true,则 resolve, 否则 reject
 */
http.validateStatus = (statusCode) => {
	return statusCode === 200
}

http.interceptor.request((config, cancel) => { /* 请求之前拦截器 */
	config.baseUrl = REQ_HOST; /* 根域名 */
	var token = apiObj.jwtToken(); 
	config.header = {
		'token':token, //header参数不允许以下划线为变量名称
	}
	if (config.method == 'GET') {
		var data = config.params || {};
		config.params = data
		config.data = '';
	} else if (config.method == 'POST') {
		var data = config.data || {}; 
		config.data = data
		config.params = '';

	}
	return config
})

http.interceptor.response((response) => { /* 请求之后拦截器 */
	var resData = response.data;
	var res = response.data;
	if(typeof res == 'string')
	{
		//如果返回的结果是字符串，需要转换为json。主要用于当http.upload的时候，data返回的是字符串
		try {
			var obj = JSON.parse(res);
			if(typeof obj == 'object' && obj ){
				res = obj;
			}
		} catch(e) {
			
		}
	}
	
	if (resData.code == 410) { // 服务端返回的状态码不等于200，则reject()
		
		apiObj.jwtToken('del'); 
		apiObj.checkLogin();
		apiObj.msg('身份验证已过期');
		//return Promise.reject(response)
	}else if(resData.code == 0)
	{
		//apiObj.msg(resData.msg)
	}
	uni.hideLoading();
	return res
}, (response) => { // 请求错误做点什么
	var res = response.data;
	console.log('储存',res)
	var req_url = response.config && response.config.url?response.config.url:'';
	if(response.statusCode == 404 || response.statusCode == 403 || response.statusCode == 444 || response.statusCode == 500 || res == '' || !res)
	{
		if(res == '' || !res)
		{
			response.statusCode = -1;
		}
		apiObj.msg(response.statusCode+'网络请求错误:'+req_url);
	}
	if (response.statusCode == 401) { // 服务端返回的状态码不等于200，则reject()
		apiObj.jwtToken('del'); 
		//apiObj.checkLogin();
		apiObj.msg('身份验证已过期');
	}
	uni.hideLoading();
	//console.log('http.interceptor' + response.errMsg);
	return response;
})


export {
	http
}
